﻿using HPIT.RentHouse.IService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HPIT.RentHouse.DTO;
using HPIT.RentHouse.Common;
using HPIT.RentHouse.Service.Entities;
using System.Web.Mvc;

namespace HPIT.RentHouse.Service
{
    [Authorize]
    public class AdminUsersService : IServiceAdminUsers
    {
        /// <summary>
        /// 获取管理员列表
        /// </summary>
        /// <param name="start"></param>
        /// <param name="length"></param>
        /// <param name="name"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public List<AdminDTO> GetAdminlist(int start, int length, string name, ref int count)
        {
            var db = new RentEntity();
            var bs = new BaseService<T_AdminUsers>(db);
            var query = PredicateExtensions.True<T_AdminUsers>();
            if (string.IsNullOrEmpty(name))
            {
                query = query
                    .And(e => e.Name.Contains(name));
            }
            var list = bs.GetPagedList(start, length, ref count, query
                , a => a.CityId == a.T_Cities.Id);
            var result = list.Select(a => new AdminDTO
            {
                Id = a.Id,
                Name = a.Name,
                PhoneNum = a.PhoneNum,
                Email = a.Email,
                CityId = a.T_Cities.Name,
            }).ToList();
            return result;
        }
        /// <summary>
        /// 添加管理员
        /// </summary>
        /// <param name="Admin"></param>
        /// <returns></returns>
        public AjaxResult Add(AdminDTO Admin)
        {
            var db = new RentEntity();
            var bs = new BaseService<T_AdminUsers>(db);
            //声明连接角色表的连接字符串
            var bsp = new BaseService<T_Roles>(db);

            //查询表中是否存在手机号和管理员名称
            var phone = bs.Get(p => p.PhoneNum == Admin.PhoneNum);
            var UserName = bs.Get(n=>n.Name==Admin.Name);
            if (phone!=null)
            {
                return new AjaxResult(ResultState.Error, "管理员添加失败，该手机号已存在");
            }
            if (UserName != null)
            {
                return new AjaxResult(ResultState.Error, "管理员添加失败，该管理员名称已存在");
            }
            //实例化类对象
            var model = new T_AdminUsers();
            model.Name = Admin.Name;
            model.PhoneNum = Admin.PhoneNum;
            model.Email = Admin.Email;
            model.CityId = Convert.ToInt32(Admin.CityId);
            model.CreateDateTime = DateTime.Now;
            model.IsDeleted = false;
            model.LoginErrorTimes = 0;
            //采用MD5加盐加密的方式  获取盐值(随机数)
            model.PasswordSalt = CommonHelper.CreateVerifyCode(5);
            //MD5加盐加密
            model.PasswordHash = CommonHelper.CalcMD5(Admin.PasswordHash+model.PasswordSalt);
            //给关联表(T_Roles添加数据)  先判断关联表中是否存在数据，存在则添加
            if (Admin.roleIds != null && Admin.roleIds.Count > 0)
            {
                foreach (var id in Admin.roleIds)
                {
                    T_Roles role = bsp.Get(a => a.Id == id);
                    model.T_Roles.Add(role);
                }
            }
            if (bs.Add(model) > 0)
            {
                return new AjaxResult(ResultState.Success, "管理员添加成功");
            }
            else
            {
                return new AjaxResult(ResultState.Error, "管理员添加失败");
            }
        }
        /// <summary>
        /// 获取城市表信息
        /// </summary>
        /// <returns></returns>
        public List<CityDTO> GetCity()
        {
            var db = new RentEntity();
            var bs = new BaseService<T_Cities>(db);
            var list = bs.GetList(a => true).Select(a => new CityDTO
            {
                Id = a.Id,
                Name = a.Name
            }).ToList();
            return list;
        }
        /// <summary>
        /// 根据id查询该条数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public AdminDTO Get(long id)
        {
            var db = new RentEntity();
            BaseService<T_AdminUsers> bs = new BaseService<T_AdminUsers>(db);
            //根据id查询该条数据是否存在
            T_AdminUsers model = bs.Get(a => a.Id == id);
            AdminDTO dto = new AdminDTO();
            if (model != null)
            {
                dto.Id = model.Id;
                dto.Name = model.Name;
                dto.PasswordHash = model.PasswordHash;
                dto.PasswordSalt = model.PasswordSalt;
                dto.Email = model.Email;
                dto.PhoneNum = model.PhoneNum;
            }
            return dto;
        }
        /// <summary>
        /// 修改管理员
        /// </summary>
        /// <param name="adminDTO"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public AjaxResult Update(AdminDTO adminDTO)
        {
            var db = new RentEntity();
            var bs = new BaseService<T_AdminUsers>(db);
            var bsp = new BaseService<T_Roles>(db);
            //先根据id查询该条数据是否存在，然后实例化类对象实现修改功能
            var model = bs.Get(e => e.Id == adminDTO.Id);
            model.Name = adminDTO.Name;           
            var salt=model.PasswordSalt;  //数据库中的盐值  
            //修改之后的密码=用户在前台输入的值+该条数据在数据库中保存的盐值
            model.PasswordHash =CommonHelper.CalcMD5(adminDTO.PasswordHash+salt);
            model.Email = adminDTO.Email;
            model.PhoneNum = adminDTO.PhoneNum;
            model.CityId = Convert.ToInt32(adminDTO.CityId);
            model.CreateDateTime = DateTime.Now;
            //修改关联表(T_Roles表)中的数据 (先删除表中该条数据已存在的角色id，然后再添加数组里的角色id)
            model.T_Roles.Clear();
            if (adminDTO.roleIds != null && adminDTO.roleIds.Count > 0)
            {
                //先通过循环获取用户选中的角色id,再调用添加方法把用户选中的角色id添加进关联表中
                foreach (var id in adminDTO.roleIds)
                {
                    T_Roles role = bsp.Get(a => a.Id == id);
                    model.T_Roles.Add(role);
                }
            }
            bool res = bs.Update(model);
            if (res)
            {
                return new AjaxResult(ResultState.Success, "管理员编辑成功！");
            }
            else
            {
                return new AjaxResult(ResultState.Error, "管理员编辑失败！");
            }
        }
        /// <summary>
        /// 删除管理员
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public AjaxResult Delete(long id)
        {
            var db = new RentEntity();
            BaseService<T_AdminUsers> bs = new BaseService<T_AdminUsers>(db);
            //根据id查询该条数据是否存在
            var model = bs.Get(a => a.Id == id);
            if (bs.Delete(model))
            {
                return new AjaxResult(ResultState.Success, "删除管理员成功！");
            }
            else
            {
                return new AjaxResult(ResultState.Error, "删除管理员失败！");
            }
        }
        /// <summary>
        /// 批量删除管理员
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public AjaxResult DeleteBatch(List<long> ids)
        {
            try
            {
                var db = new RentEntity();
                BaseService<T_AdminUsers> bs = new BaseService<T_AdminUsers>(db);
                //通过循环获取用户选中的多个id,并查询出数据，实现批量删除
                foreach (var id in ids)
                {
                    var model = bs.Get(a => a.Id == id);
                    bs.Delete(model);
                }
                return new AjaxResult(ResultState.Success, "批量删除成功！");
            }
            catch (Exception)
            {
                return new AjaxResult(ResultState.Error, "批量删除失败！");
            }
        }
    }
}
